package erfgame.core.world.terrain.color;

import java.util.Random;


import erfgame.core.util.ColorUtils;
import erfgame.core.world.terrain.TerrainColorSource;

public class SampledTerrainColorSource implements TerrainColorSource {

	public static final int getRandomColor( int minColor, int maxColor, Random random ) {
		int minr = 0xFF0000 & minColor;
		int maxr = 0xFF0000 & maxColor;
		int ming = 0x00FF00 & minColor;
		int maxg = 0x00FF00 & maxColor;
		int minb = 0x0000FF & minColor;
		int maxb = 0x0000FF & maxColor;
		
		double fraction = random.nextDouble();
		int r = minr + (int)((double)(maxr - minr)*fraction);
		int g = ming + (int)((double)(maxg - ming)*fraction);
		int b = minb + (int)((double)(maxb - minb)*fraction);
		return (r & 0xFF0000) | (g & 0x00FF00 ) | (b & 0x0000FF ); 
	}

	public static final int[] getRandomColors( int minColor, int maxColor, Random random, int[] into ) {
		int minr = 0xFF0000 & minColor;
		int maxr = 0xFF0000 & maxColor;
		int ming = 0x00FF00 & minColor;
		int maxg = 0x00FF00 & maxColor;
		int minb = 0x0000FF & minColor;
		int maxb = 0x0000FF & maxColor;
		
		for( int i = into.length; i>0; ) {
			i--;
			// TODO : this can be done with ints
			double fraction = random.nextDouble();
			int r = minr + (int)((double)(maxr - minr)*fraction);
			int g = ming + (int)((double)(maxg - ming)*fraction);
			int b = minb + (int)((double)(maxb - minb)*fraction);
			into[i] = (r & 0xFF0000) | (g & 0x00FF00 ) | (b & 0x0000FF ); 
		}		
		return into;
	}
	
	private int[] colors;
	private int[] minColors;
	private int[] maxColors;
	
	public SampledTerrainColorSource( int[] minColors, int[] maxColors, int[] colors ) {
		this.colors = colors;
		this.minColors = minColors;
		this.maxColors = maxColors;
	}
	
	public int getColor(int x, int y, int z, int mult, int div, int dCeiling) {
		int sample = ( x*y*z + x+y+z )%this.colors.length;
		int baseColor = this.colors[ sample ];
		int color;
		if( mult > 0 ) {
			int extreme = this.maxColors[ sample ];
			color = ColorUtils.multiplyColor(baseColor, extreme, mult, div );
		} else {
			int extreme = this.minColors[ sample ];
			color = ColorUtils.multiplyColor( baseColor, extreme, -mult, div );
		}
		return color;
	}
}
